#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2008 Thibauld Favre <tfavre@gmail.com>
#
# Author:
#  Thibauld Favre
#
# This program is free software; you can redistribute it and/or modify it under
# the terms of the GNU General Public License as published by the Free Software
# Foundation; either version 2 of the License, or (at your option) any later
# version.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 59 Temple
# Place, Suite 330, Boston, MA 02111-1307 USA

import os
import sys 
from smcagent import SMCAgent
from smcagent.xmlnode import XMLNode
import signal
from optparse import OptionParser

api_key = 'LOCAL_TEST'
app_version = "%prog 0.9.0"
app_usage = '''
%prog -s <script.zip> -p <params.xml>

This tool helps creating and debugging scripts locally. Once the script runs
as expected locally. It can be uploaded onto savemyconf server to be used
from there.'''

def execution_finished(id,end_status):
    print "Local request with id: %i ended with status: %s" % (id, end_status)

def stop(*args):  SMCAgent.listen = False

if __name__ == "__main__":
    parser = OptionParser(version=app_version)
    parser.set_usage(app_usage)
    parser.add_option('-s','--script', dest='script', metavar='SCRIPT', help='script file (zipped) to be executed')
    parser.add_option('-p','--params', dest='parameters', metavar='PARAMS_FILE', help='script parameters (xml formatted)')
    options, args = parser.parse_args()

    if not options.script:
        parser.error("No script specified.")
    if not options.parameters:
        parser.error("No parameters specified.")

    file = open(options.parameters)
    data=file.read()
    rsp = XMLNode.parseXML(data, True)
    req_id = rsp.request[0]['rq_id']
    req_name = rsp.request[0]['name']
    req_files = {}
    req_params = {}
    for item in rsp.request[0].files[0].file:
        req_files[item.name[0].elementText] = item.url[0].elementText
    for item in rsp.request[0].configuration[0].property:
        req_params[item.name[0].elementText] = item.value[0].elementText

    script_url = os.path.abspath(options.script)
    a = SMCAgent(api_key)
    a.run_local_script(script_url,req_params,req_files,execution_finished);
            

